<template>
  <common-page title="AI智能监控" :istabs="true" class="warn-page">
    <div class="video-tree-container">
      <div class="ship-tree-panel">
        <!-- <el-select class="company-selector" v-model="companyId" filterable placeholder="请选择" @change="companySelectChange">
          <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select> -->
        <el-input placeholder="输入关键字进行过滤" v-model="filterText">
        </el-input>
        <el-tree :props="props" ref="shipTree" :load="loadNode" lazy @node-click="handleTreeNodeClick"
          :filter-node-method="filterNode">
          <span slot-scope="{ node ,data}" class="treeIcon">
            <el-tooltip class="item" effect="dark" :content="node.label" placement="left">
              <span v-if="node.level > 1"> {{ node.label }}（{{ data.cameraNumber || '0' }}） </span>
              <span v-else>{{ node.label }}</span>
            </el-tooltip>
            <div></div>
          </span>
        </el-tree>
        <!-- <el-tree ref="shipTree" :default-expanded-keys="shipTreeExpandKeys" :data="shipTreeData" :props="defaultTreeProps" node-key="id" @node-click="handleTreeNodeClick">
          <span slot-scope="{ node ,data}" class="treeIcon">
            <el-tooltip class="item" effect="dark" :content="node.label" placement="left">
              <span> {{ node.label }}（{{ data.cameraNumber|| '0' }}） </span>
            </el-tooltip>
            <div></div>
          </span>
        </el-tree> -->
      </div>
      <div v-if="videoList && videoList.length > 0" class="video-list">
        <!-- <ship-video></ship-video>
          <ship-video></ship-video>
          <ship-video></ship-video>
          <ship-video></ship-video> -->
        <div v-for="video in videoList" :key="video.id" class="video-item">
          <div class="top">
            <span class="iconfont icon-ship">{{ video.shipName }}</span>
            <span>点位：{{ video.installationPointText }}</span>
          </div>
          <div class="video-panel" :style="getShotcutImgStyle(video.imageThumb)">
            <img v-if="video.status == '1'" src="@/assets/images/video-play.png" @click="playVideo(video, true)" />
            <div class="video-status">
              <div class="icon" :class="video.status == '1' ? 'online-icon' : 'offline-icon'"></div>
              <span class="text">{{ video.status == '1' ? '在线' : '离线' }}</span>
            </div>
          </div>
          <div class="history-setting">
            <el-date-picker v-model="video.timeRange" size="mini" value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange" :editable="false" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"
              :default-time="['00:00:00', '23:59:59']" @change="(e) => {
    timeRangeChanged(video, e)
  }
    ">
            </el-date-picker>
            <el-button type="primary" class="history-btn" size="mini" @click="playVideo(video, false)">回放</el-button>
          </div>
        </div>
      </div>
      <el-empty v-else class="empty-panel" description="暂无摄像头数据"></el-empty>
    </div>

    <VideoDialog ref="videoDialog"></VideoDialog>
    <!-- <video ref="video" class="video" autoplay muted></video> -->
  </common-page>
</template>
<script>
import VideoDialog from '@/components/video-dialog'
import { createNamespacedHelpers } from 'vuex'
import { getTenantShipTree } from '@/api/ship'
import { getCameraListByShipId, getTenantBySupervise } from '@/api/video'
const { mapState } = createNamespacedHelpers('user')
export default {
  name: 'VideoRealtime',
  components: {
    VideoDialog
  },
  data() {
    return {
      searchParam: {
        shipId: '',
        installationPoint: undefined,
        status: undefined
      },
      companyList: [],
      companyId: undefined,

      defaultTreeProps: {
        children: 'children',
        label: 'name'
      },
      installationPointList: [],
      // value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
      value1: undefined,
      shipTreeData: [],
      shipTreeExpandKeys: [],
      currentShip: {},
      videoList: [],
      filterText: '',
      props: {
        label: 'name',
        children: 'zones',
        isLeaf: 'leaf'
      },
    }
  },
  computed: {
    ...mapState(['tenantId'])
  },
  watch: {
    filterText(val) {
      this.$refs.shipTree.filter(val);
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    getQueryParams() {
      if (this.$route.query) {
        if (this.$route.query.shipId) {
          this.searchParam.shipId = this.$route.query.shipId
        }
      }
    },
    filterNode(value, data) {
      console.log("🚀 ~  value, data: ", value, data)
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    async loadNode(node, resolve) {
      console.log("🚀 ~  node: ", node.level)
      if (node.level === 0) {
        const companyResult = await getTenantBySupervise(this.tenantId)
        if (companyResult.result && companyResult.result.length > 0) {
          this.companyList = companyResult.result
        }
        resolve(this.companyList)
        // return resolve(this.companyList);
      }
      if (node.level === 1) {

        const queryTennantResult = await getTenantShipTree(node.data.id)
        if (queryTennantResult.result && queryTennantResult.result.length > 0) {
          this.shipTreeData = queryTennantResult.result
          this.shipTreeData.forEach(val => {
            if (val && val.children && val.children.length > 0) {
              val.children = val.children.filter(vv => vv.cameraNumber > 0)
            }
          });
          return resolve(this.shipTreeData);
        }
      }
      if (node.level === 2) {
        node.data.children.map(v => v.leaf = true)
        return resolve(node.data.children);
      }
      if (node.level > 2) {
        return resolve([]);
      }
    },
    async initData() {
      // const installationPointResult = await getDict({code: "installation_point"})
      // if (installationPointResult.result && installationPointResult.result.length > 0) {
      //     this.installationPointList = installationPointResult.result
      // }
      //const companyResult = await getTenantShipTree('1623125671454371841');
      const companyResult = await getTenantBySupervise(this.tenantId)
      if (companyResult.result && companyResult.result.length > 0) {
        this.companyList = companyResult.result
      }
      if (this.companyList && this.companyList.length > 0) {
        this.companyId = this.companyList[0].id
        this.switchVideoTree(this.companyId)
      }
    },
    companySelectChange(companyId) {
      this.switchVideoTree(companyId)
    },
    // 切换视频树结构
    async switchVideoTree(companyId) {
      const queryTennantResult = await getTenantShipTree(companyId)
      if (queryTennantResult.result && queryTennantResult.result.length > 0) {
        this.shipTreeData = queryTennantResult.result
        this.shipTreeData.forEach(val => {
          if (val && val.children && val.children.length > 0) {
            val.children = val.children.filter(vv => vv.cameraNumber > 0)
          }
        });
        // if (this.$route.query && this.$route.query.shipId) {
        //   this.currentShip = this.shipTreeData.find(item => item.code == this.$route.query.shipId)
        // }
        // if (!this.currentShip.code) {
        //   this.currentShip = this.shipTreeData[0];
        // }
        this.currentShip = this.shipTreeData[0]
        this.shipTreeExpandKeys = [this.currentShip.code]

        this.searchParam.shipId = this.currentShip.code
        this.$nextTick(() => {
          // if (this.$route.query && this.$route.query.installationPoint) {
          //   this.searchParam.installationPoint = this.$route.query.installationPoint
          //   this.$refs.shipTree.setCurrentKey(this.searchParam.shipId + "_" + this.searchParam.installationPoint);
          // } else {
          //   this.$refs.shipTree.setCurrentKey(this.searchParam.shipId);
          // }
          // this.$refs.shipTree.setCurrentKey(this.searchParam.shipId)
          this.queryVideoList()
        })
      } else {
        this.shipTreeData = []
        this.videoList = []
      }
    },
    // 查询摄像头列表
    queryVideoList() {
      getCameraListByShipId(this.searchParam)
        .then((res) => {
          if (res.result && res.result.length > 0) {
            this.videoList = res.result.map((val) => {
              return {
                timeRange: undefined,
                id: val.id, //val.cameraCode,
                channel: val.channel,
                shipName: this.currentShip?.name,
                shipcatCode: val.shipcatCode,
                status: val.cameraStatus, // ? val.cameraStatus : "在线",
                installationPointText: val.installationPointName, // val.installationPoint ? dictUtil.getDictLabelByList(val.installationPoint,this.installationPointList,"") : "未知",
                imageThumb: val.imageThumb,
                cameraType: val.cameraType
              }
            })
          } else {
            this.videoList = []
            // this.$message.warning("当前选中船舶没有安装摄像头！")
          }
        })
        .catch(() => {
          this.videoList = []
        })
    },

    onShipChange(id) {
      if (this.shipTreeData && this.shipTreeData.length > 0) {
        const shipItem = this.shipTreeData.find((val) => val.id === id)
        if (shipItem) {
          this.currentShip = shipItem
        }
      }
    },
    handleTreeNodeClick(data, node) {
      console.log("🚀 ~  data, node: ", data, node)
      let shipId, installationPoint
      if (data.type === 'installation_point') {
        installationPoint = data.code
        this.currentShip = node.parent.data
        shipId = this.currentShip.id
      } else if (data.type === 'ship') {
        this.currentShip = data
        shipId = data.code
      }
      if (this.searchParam.shipId != shipId || this.searchParam.installationPoint != installationPoint) {
        this.searchParam.shipId = shipId
        this.searchParam.installationPointType = installationPoint
        if (shipId) {
          this.queryVideoList()
        }

      }
    },
    playVideo(video, isRealTime) {
      const videoInfo = { ...video }
      if (isRealTime) {
        videoInfo.timeRange = undefined
      } else {
        if (!videoInfo.timeRange || videoInfo.timeRange.length != 2) {
          this.$message.warning('请选择时间范围！')
          return
        }
      }
      this.$refs.videoDialog?.open(videoInfo)
    },
    // 获取缩略图样式
    getShotcutImgStyle(imgUrl) {
      if (imgUrl) {
        const picUrl = `${process.env.VUE_APP_MINIO}${this.$setting.downloadUrl}?objectName=` + encodeURIComponent(imgUrl)
        return `background-image:url('${picUrl}')`
      }
      return ''
    },
    timeRangeChanged(video, timeInfo) {
      if (timeInfo && timeInfo.length == 2) {
        const now = new Date()
        const startTime = new Date(timeInfo[0])
        const timeEnd = new Date(timeInfo[1])
        if (timeEnd.getTime() > now.getTime()) {
          this.$message.warning('历史时间范围不能包含未来时间')
          video.timeRange = undefined
          return
        }
        if (timeEnd.getTime() - startTime.getTime() < 10000) {
          this.$message.warning('历史时间范围不能小于10秒')
          video.timeRange = undefined
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 18px;
}

::v-deep .el-range-editor.el-input__inner {
  padding: 3px 5px;
}

.app-view {
  //margin:0 !important;
}

.page-card {
  height: calc(100% - 40px) !important;
}

.video-tree-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: nowrap;
  justify-content: flex-start;

  .ship-tree-panel {
    width: 220px;
    height: 100%;
    padding: 0px 20px 10px 10px;
    border-right: 2px solid #e1e1e1;
    flex-shrink: 0;

    .company-selector {
      margin-bottom: 10px;
    }
  }

  .empty-panel {
    flex-grow: 1;
  }

  .video-list {
    margin-left: 20px;
    margin-top: 0px;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    align-items: center;
    align-self: flex-start;
    min-width: 1200px;
    max-width: 1600px;

    .video-item {
      padding: 10px;
      background: #fafcff;
      box-shadow: 0px 1px 5px 0px rgba(0, 89, 206, 0.16);
      border-radius: 6px;
      margin-right: 10px;
      margin-bottom: 10px;

      .top,
      .history-setting {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0px;
        width: 370px;
      }

      .top span:first-child {
        font-size: 16px;

        font-weight: 600;
        color: #333333;
      }

      .top span:nth-child(2) {
        font-size: 14px;
        font-weight: 400;
        color: #333333;
      }

      .icon-ship:before {
        margin-right: 9px;
      }

      .history-btn {
        margin-left: 10px;
      }

      .video-panel {
        width: 370px;
        height: 208px;
        background: rgb(223, 223, 223);
        position: relative;
        //background-image: url('~@/assets/images/video-bg.png');
        background-color: #e9eff7;
        background-size: cover;
        background-position: center center;

        img {
          position: absolute;
          left: calc(50% - 28px);
          top: calc(50% - 28px);
          cursor: pointer;
        }

        .video-status {
          position: absolute;
          right: 10px;
          top: 10px;
          display: flex;
          justify-content: center;
          align-items: center;

          .icon {
            width: 10px;
            height: 10px;
            border-radius: 10px;
            margin-right: 5px;
          }

          .online-icon {
            background-color: #65c65c;
          }

          .offline-icon {
            background-color: #b2b2b2;
          }

          .text {
            font-size: 14px;
            color: #ffffff;
            line-height: 14px;
          }
        }
      }
    }
  }
}

.treeIcon {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px;
}

.warn-page {
  min-height: 100% !important;

  ::v-deep .pagecard {
    min-height: calc(100vh - 3.8vw - 40px);

    .content {
      min-height: calc(100vh - 3.8vw - 40px - 48px - 40px);

      .video-tree-container {
        min-height: calc(100vh - 3.8vw - 40px - 48px - 40px - 30px);

        .ship-tree-panel {
          min-height: 100%;
          height: auto;
        }
      }
    }
  }
}
</style>
